<template>
  <div class="brand-extractor">
    <!-- 对话框模式 -->
    <el-dialog
      v-if="!pageMode"
      v-model="dialogVisible"
      :title="isFullscreen ? '' : '品牌提取器'"
      width="80%"
      :fullscreen="isFullscreen"
      destroy-on-close
    >
      <template #header="{ close }" >
        <div class="dialog-header">
          <span class="dialog-title">品牌提取器</span>
          <div>
            <el-button 
              type="primary" 
              plain 
              size="small" 
              @click="isFullscreen = false" 
              circle
            >
              <el-icon><FullScreen /></el-icon>
            </el-button>
            <el-button 
              type="danger" 
              plain 
              size="small" 
              @click="close" 
              circle
            >
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="main-container">
        <!-- 顶部功能栏 -->
        <div class="top-action-bar" v-if="!isFullscreen">
          <div></div>
          <el-button 
            type="primary" 
            size="small" 
            @click="isFullscreen = true" 
            title="全屏显示"
          >
            <el-icon><FullScreen /></el-icon>
            全屏显示
          </el-button>
        </div>
        
        <!-- 步骤指示器 -->
        <el-steps :active="activeStep" align-center finish-status="success">
          <el-step title="导入商品" :icon="Upload" />
          <el-step title="提取品牌" :icon="Star" />
          <el-step title="确认新品牌" :icon="InfoFilled" />
          <el-step title="完成" :icon="Check" />
        </el-steps>

        <!-- 步骤1: 输入商品数据 -->
        <div v-if="activeStep === 0" class="step-container">
          <div class="step-description">
            <el-alert title="请输入需要提取品牌的商品名称列表，每行一个商品" type="info" :closable="false" />
          </div>
          
          <div class="input-container">
            <p class="step-description">请输入商品名称列表，每行一个商品</p>
            <el-input
              v-model="productTextarea"
              type="textarea"
              :rows="10"
              placeholder="输入商品名称，每行一个"
            />
            <div class="textarea-footer">
              <span>已输入 {{ productCount || 0 }} 个商品</span>
              <el-upload
                class="upload-area"
                action=""
                :auto-upload="false"
                :show-file-list="false"
                accept=".txt,.csv,.xlsx,.xls"
                :on-change="handleFileUpload"
              >
                <el-button type="primary" plain size="small">
                  <el-icon><Upload /></el-icon>上传文件
                </el-button>
              </el-upload>
            </div>
            <div class="file-type-hint">支持TXT、CSV、Excel文件格式</div>
          </div>
        </div>

        <!-- 步骤2: 提取潜在品牌 -->
        <div v-if="activeStep === 1" class="step-container">
          <div v-if="loading.extract" class="loading-container">
            <el-skeleton :rows="6" animated />
            <p>正在分析商品数据，提取潜在品牌...</p>
          </div>
          <div v-else class="extract-results">
            <div class="result-summary">
              <el-alert
                title="品牌提取结果"
                type="success"
                :closable="false"
                show-icon
              >
                系统已分析商品，提取出潜在品牌。
              </el-alert>
            </div>
            
            <div class="brand-lists">
              <div class="unknown-brands">
                <div class="unknown-brands-header">
                  <h4>发现的潜在品牌 ({{ extractedBrands.length }})</h4>
                  <div class="unknown-brands-actions">
                    <el-tooltip content="批量操作">
                      <el-button
                        size="small"
                        type="primary"
                        plain
                        :disabled="selectedBrands.length === 0"
                        @click="handleBatchOperation"
                      >
                        批量操作
                      </el-button>
                    </el-tooltip>
                  </div>
                </div>
                
                <el-table
                  v-if="isTableReady"
                  :data="extractedBrands"
                  style="width: 100%"
                  @selection-change="handleSelectionChange"
                  v-loading="loading.tableLoading"
                >
                  <el-table-column type="selection" width="55" />
                  <el-table-column label="品牌名称" prop="brandName">
                    <template #default="{ row }">
                      <div class="brand-input-wrapper">
                        <el-input 
                          v-model="row.brandName" 
                          size="small"
                          placeholder="品牌名称"
                        />
                        <div class="brand-status-indicators">
                          <el-tag 
                            size="small" 
                            :type="getConfidenceType(row.confidence)"
                            class="confidence-tag"
                          >
                            可信度: {{ formatConfidence(row.confidence) }}
                          </el-tag>
                          <span v-if="row.matchCount" class="feedback-indicator">
                            匹配: {{ row.matchCount }}
                          </span>
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="出现次数" prop="matchCount" width="100" />
                  <el-table-column label="样例" prop="examples" width="200">
                    <template #default="{ row }">
                      <el-tooltip 
                        :content="row.examples ? row.examples.join('\n') : '无样例'" 
                        placement="top"
                      >
                        <el-button link type="primary" size="small">
                          查看样例
                        </el-button>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="150">
                    <template #default="{ row, $index }">
                      <el-button 
                        type="success" 
                        size="small" 
                        circle
                        @click="confirmBrand(row)"
                        title="确认为品牌"
                      >
                        <el-icon><Check /></el-icon>
                      </el-button>
                      <el-button 
                        type="danger" 
                        size="small" 
                        circle
                        @click="rejectBrand(row, $index)"
                        title="不是品牌"
                      >
                        <el-icon><Delete /></el-icon>
                      </el-button>
                      <el-button 
                        type="primary" 
                        size="small" 
                        circle
                        @click="editBrandDetails(row)"
                        title="编辑详情"
                      >
                        <el-icon><Edit /></el-icon>
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                
                <div class="pagination">
                  <el-pagination
                    v-if="extractedBrands.length > pageSize"
                    layout="prev, pager, next"
                    :total="extractedBrands.length"
                    :page-size="pageSize"
                    @current-change="handlePageChange"
                  />
                </div>
              </div>
              
              <div class="known-brands">
                <div class="known-brands-header">
                  <h4>已确认品牌 ({{ confirmedBrands.length }})</h4>
                </div>
                
                <el-table
                  v-if="isTableReady"
                  :data="confirmedBrands"
                  style="width: 100%"
                >
                  <el-table-column label="品牌名称" prop="brandName" />
                  <el-table-column label="分类" prop="category" width="120" />
                  <el-table-column label="操作" width="100">
                    <template #default="{ row, $index }">
                      <el-button 
                        type="danger" 
                        size="small" 
                        circle
                        @click="moveToUnconfirmed(row, $index)"
                        title="移回未确认"
                      >
                        <el-icon><Close /></el-icon>
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </div>

        <!-- 步骤3: 确认新品牌 -->
        <div v-if="activeStep === 2" class="step-container">
          <div class="step-description">
            <el-alert title="请确认以下新发现的品牌" type="info" :closable="false" />
          </div>
          
          <div class="confirm-container">
            <p>确认品牌列表</p>
          </div>
        </div>

        <!-- 步骤4: 完成 -->
        <div v-if="activeStep === 3" class="step-container">
          <div class="completion-container">
            <el-result
              icon="success"
              title="品牌提取完成"
              sub-title="新品牌已成功添加到系统"
            >
              <template #extra>
                <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
              </template>
            </el-result>
          </div>
        </div>

        <!-- 步骤按钮 -->
        <div class="step-buttons">
          <el-button v-if="activeStep > 0" @click="prevStep">上一步</el-button>
          <el-button 
            v-if="activeStep < 3" 
            type="primary" 
            @click="nextStep"
            :disabled="loading.allSteps"
            :loading="loading.extract && activeStep === 0"
          >
            {{ stepButtonText }}
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 页面模式直接显示内容 -->
    <div v-if="pageMode" class="page-mode-container">
      <div class="main-container">
        <!-- 步骤指示器 -->
        <el-steps :active="activeStep" align-center finish-status="success">
          <el-step title="导入商品" :icon="Upload" />
          <el-step title="提取品牌" :icon="Star" />
          <el-step title="确认新品牌" :icon="InfoFilled" />
          <el-step title="完成" :icon="Check" />
        </el-steps>

        <!-- 步骤1: 输入商品数据 -->
        <div v-if="activeStep === 0" class="step-container">
          <div class="step-description">
            <el-alert title="请输入需要提取品牌的商品名称列表，每行一个商品" type="info" :closable="false" />
          </div>
          
          <div class="input-container">
            <p class="step-description">请输入商品名称列表，每行一个商品</p>
            <el-input
              v-model="productTextarea"
              type="textarea"
              :rows="10"
              placeholder="输入商品名称，每行一个"
            />
            <div class="textarea-footer">
              <span>已输入 {{ productCount || 0 }} 个商品</span>
              <el-upload
                class="upload-area"
                action=""
                :auto-upload="false"
                :show-file-list="false"
                accept=".txt,.csv,.xlsx,.xls"
                :on-change="handleFileUpload"
              >
                <el-button type="primary" plain size="small">
                  <el-icon><Upload /></el-icon>上传文件
                </el-button>
              </el-upload>
            </div>
            <div class="file-type-hint">支持TXT、CSV、Excel文件格式</div>
          </div>
        </div>

        <!-- 步骤2: 提取潜在品牌 -->
        <div v-if="activeStep === 1" class="step-container">
          <div v-if="loading.extract" class="loading-container">
            <el-skeleton :rows="6" animated />
            <p>正在分析商品数据，提取潜在品牌...</p>
          </div>
          <div v-else class="extract-results">
            <div class="result-summary">
              <el-alert
                title="品牌提取结果"
                type="success"
                :closable="false"
                show-icon
              >
                系统已分析商品，提取出潜在品牌。
              </el-alert>
            </div>
            
            <div class="brand-lists">
              <div class="unknown-brands">
                <div class="unknown-brands-header">
                  <h4>发现的潜在品牌 ({{ extractedBrands.length }})</h4>
                  <div class="unknown-brands-actions">
                    <el-tooltip content="批量操作">
                      <el-button
                        size="small"
                        type="primary"
                        plain
                        :disabled="selectedBrands.length === 0"
                        @click="handleBatchOperation"
                      >
                        批量操作
                      </el-button>
                    </el-tooltip>
                  </div>
                </div>
                
                <el-table
                  v-if="isTableReady"
                  :data="extractedBrands"
                  style="width: 100%"
                  @selection-change="handleSelectionChange"
                  v-loading="loading.tableLoading"
                >
                  <el-table-column type="selection" width="55" />
                  <el-table-column label="品牌名称" prop="brandName">
                    <template #default="{ row }">
                      <div class="brand-input-wrapper">
                        <el-input 
                          v-model="row.brandName" 
                          size="small"
                          placeholder="品牌名称"
                        />
                        <div class="brand-status-indicators">
                          <el-tag 
                            size="small" 
                            :type="getConfidenceType(row.confidence)"
                            class="confidence-tag"
                          >
                            可信度: {{ formatConfidence(row.confidence) }}
                          </el-tag>
                          <span v-if="row.matchCount" class="feedback-indicator">
                            匹配: {{ row.matchCount }}
                          </span>
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="出现次数" prop="matchCount" width="100" />
                  <el-table-column label="样例" prop="examples" width="200">
                    <template #default="{ row }">
                      <el-tooltip 
                        :content="row.examples ? row.examples.join('\n') : '无样例'" 
                        placement="top"
                      >
                        <el-button link type="primary" size="small">
                          查看样例
                        </el-button>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="150">
                    <template #default="{ row, $index }">
                      <el-button 
                        type="success" 
                        size="small" 
                        circle
                        @click="confirmBrand(row)"
                        title="确认为品牌"
                      >
                        <el-icon><Check /></el-icon>
                      </el-button>
                      <el-button 
                        type="danger" 
                        size="small" 
                        circle
                        @click="rejectBrand(row, $index)"
                        title="不是品牌"
                      >
                        <el-icon><Delete /></el-icon>
                      </el-button>
                      <el-button 
                        type="primary" 
                        size="small" 
                        circle
                        @click="editBrandDetails(row)"
                        title="编辑详情"
                      >
                        <el-icon><Edit /></el-icon>
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                
                <div class="pagination">
                  <el-pagination
                    v-if="extractedBrands.length > pageSize"
                    layout="prev, pager, next"
                    :total="extractedBrands.length"
                    :page-size="pageSize"
                    @current-change="handlePageChange"
                  />
                </div>
              </div>
              
              <div class="known-brands">
                <div class="known-brands-header">
                  <h4>已确认品牌 ({{ confirmedBrands.length }})</h4>
                </div>
                
                <el-table
                  v-if="isTableReady"
                  :data="confirmedBrands"
                  style="width: 100%"
                >
                  <el-table-column label="品牌名称" prop="brandName" />
                  <el-table-column label="分类" prop="category" width="120" />
                  <el-table-column label="操作" width="100">
                    <template #default="{ row, $index }">
                      <el-button 
                        type="danger" 
                        size="small" 
                        circle
                        @click="moveToUnconfirmed(row, $index)"
                        title="移回未确认"
                      >
                        <el-icon><Close /></el-icon>
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </div>

        <!-- 步骤3: 确认新品牌 -->
        <div v-if="activeStep === 2" class="step-container">
          <div class="step-description">
            <el-alert title="请确认以下新发现的品牌" type="info" :closable="false" />
          </div>
          
          <div class="confirm-container">
            <p>确认品牌列表</p>
          </div>
        </div>

        <!-- 步骤4: 完成 -->
        <div v-if="activeStep === 3" class="step-container">
          <div class="completion-container">
            <el-result
              icon="success"
              title="品牌提取完成"
              sub-title="新品牌已成功添加到系统"
            >
              <template #extra>
                <el-button type="primary" @click="$emit('complete', { success: true, addedCount: 2, needsRefresh: true })">返回</el-button>
              </template>
            </el-result>
          </div>
        </div>
        
        <!-- 步骤按钮 -->
        <div class="step-buttons">
          <el-button v-if="activeStep > 0" @click="prevStep">上一步</el-button>
          <el-button 
            v-if="activeStep < 3" 
            type="primary" 
            @click="nextStep"
            :disabled="loading.allSteps"
            :loading="loading.extract && activeStep === 0"
          >
            {{ stepButtonText }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { FullScreen, Close, Edit, Check, Delete, View, Star, InfoFilled, Upload } from '@element-plus/icons-vue';
import { extractBrands, saveBrands, addToNonBrands } from '@/api/brand';
import * as XLSX from 'xlsx';
import { suppressResizeObserverErrors } from '@/utils/resizeObserverErrorHandler';

// 系统级错误处理器
let originalOnError = null;
let originalConsoleError = null;
const removeErrorHandler = () => {
  if (typeof window !== 'undefined') {
    if (originalOnError) {
      window.onerror = originalOnError;
      originalOnError = null;
    }
    if (originalConsoleError) {
      console.error = originalConsoleError;
      originalConsoleError = null;
    }
  }
};

// 全局添加ResizeObserver错误处理器，抑制错误显示
if (typeof window !== 'undefined') {
  // 保存原始的错误处理器
  originalOnError = window.onerror;
  
  // 覆盖onerror
  window.onerror = function(msg, url, line, column, error) {
    // 彻底忽略ResizeObserver错误
    if (msg && typeof msg === 'string' && msg.includes('ResizeObserver')) {
      // 不输出日志
      return true;
    }
    // 忽略webpack-dev-server相关错误
    if (url && typeof url === 'string' && url.includes('webpack-dev-server')) {
      return true;
    }
    // 其他错误使用原始处理器
    return originalOnError ? originalOnError(msg, url, line, column, error) : false;
  };
  
  // 直接捕获并抑制控制台错误
  originalConsoleError = console.error;
  console.error = function(...args) {
    if (args.length > 0) {
      const firstArg = args[0];
      if (
        (typeof firstArg === 'string' && firstArg.includes('ResizeObserver')) ||
        (firstArg instanceof Error && firstArg.message && firstArg.message.includes('ResizeObserver'))
      ) {
        // 忽略ResizeObserver错误，不输出任何日志
        return;
      }
    }
    return originalConsoleError.apply(console, args);
  };
  
  // 添加DOM样式来隐藏错误覆盖层
  const addOverlayHideStyles = () => {
    const style = document.createElement('style');
    style.textContent = `
      #webpack-dev-server-client-overlay[data-message*="ResizeObserver"] {
        display: none !important;
      }
    `;
    document.head.appendChild(style);
  };
  
  // 在DOM加载后添加样式
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', addOverlayHideStyles);
  } else {
    addOverlayHideStyles();
  }
}

// 组件卸载时恢复原始错误处理
onBeforeUnmount(() => {
  removeErrorHandler();
});

// 定义props和emits
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  pageMode: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:modelValue', 'complete']);

// 对话框状态
const isFullscreen = ref(true);
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
});

// 商品文本区内容
const productTextarea = ref('');
// 计算商品数量
const productCount = computed(() => {
  const lines = productTextarea.value.split('\n').filter(line => line.trim().length > 0);
  return lines.length;
});

// 当前步骤
const activeStep = ref(0);

// 加载状态
const loading = ref({
  extract: false,
  save: false,
  allSteps: false,
  tableLoading: false
});

// 提取的品牌列表
const extractedBrands = ref([]);
// 已确认的品牌列表
const confirmedBrands = ref([]);
// 选中的品牌
const selectedBrands = ref([]);
// 分页设置
const pageSize = ref(10);
const currentPage = ref(1);

// 步骤按钮文本
const stepButtonText = computed(() => {
  switch (activeStep.value) {
    case 0:
      return '开始提取';
    case 1:
      return '下一步: 确认品牌';
    case 2:
      return '完成';
    default:
      return '下一步';
  }
});

// 格式化可信度
const formatConfidence = (confidence) => {
  if (!confidence) return '未知';
  const value = parseFloat(confidence);
  return value.toFixed(2);
};

// 获取可信度类型
const getConfidenceType = (confidence) => {
  if (!confidence) return '';
  const value = parseFloat(confidence);
  if (value >= 0.8) return 'success';
  if (value >= 0.5) return 'primary';
  return 'warning';
};

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedBrands.value = selection;
};

// 处理页面变化
const handlePageChange = (page) => {
  currentPage.value = page;
};

// 确认品牌
const confirmBrand = (brand) => {
  // 复制品牌到已确认列表
  confirmedBrands.value.push({
    ...brand,
    category: '未分类' // 默认分类
  });
  
  // 从提取列表中移除
  const index = extractedBrands.value.findIndex(item => item.brandName === brand.brandName);
  if (index > -1) {
    extractedBrands.value.splice(index, 1);
  }
  
  ElMessage.success(`已确认品牌: ${brand.brandName}`);
};

// 拒绝品牌
const rejectBrand = (brand, index) => {
  ElMessageBox.confirm(`确定"${brand.brandName}"不是品牌吗？`, '确认操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    extractedBrands.value.splice(index, 1);
    ElMessage.success(`已移除: ${brand.brandName}`);
  }).catch(() => {});
};

// 编辑品牌详情
const editBrandDetails = (brand) => {
  ElMessageBox.prompt(`请编辑品牌 "${brand.brandName}" 的名称`, '编辑品牌', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: brand.brandName
  }).then(({ value }) => {
    if (value && value.trim() !== '') {
      brand.brandName = value.trim();
      ElMessage.success(`品牌名称已更新为: ${value}`);
    }
  }).catch(() => {});
};

// 将品牌从已确认移回未确认
const moveToUnconfirmed = (brand, index) => {
  // 从已确认列表中移除
  confirmedBrands.value.splice(index, 1);
  
  // 添加回提取列表
  extractedBrands.value.push({
    ...brand,
    category: undefined
  });
  
  ElMessage.info(`已将 ${brand.brandName} 移回未确认列表`);
};

// 批量操作
const handleBatchOperation = () => {
  if (selectedBrands.value.length === 0) {
    ElMessage.warning('请先选择品牌');
    return;
  }
  
  ElMessageBox.confirm(
    `您选择了 ${selectedBrands.value.length} 个品牌，请选择操作:`, 
    '批量操作', 
    {
      confirmButtonText: '批量确认',
      cancelButtonText: '批量删除',
      distinguishCancelAndClose: true,
      type: 'warning'
    }
  ).then(() => {
    // 批量确认
    selectedBrands.value.forEach(brand => {
      confirmBrand(brand);
    });
    ElMessage.success(`已批量确认 ${selectedBrands.value.length} 个品牌`);
    selectedBrands.value = [];
  }).catch(action => {
    if (action === 'cancel') {
      // 批量删除
      const brandNames = selectedBrands.value.map(brand => brand.brandName);
      extractedBrands.value = extractedBrands.value.filter(
        brand => !brandNames.includes(brand.brandName)
      );
      ElMessage.success(`已批量删除 ${brandNames.length} 个品牌`);
      selectedBrands.value = [];
    }
  });
};

// 处理文件上传
const handleFileUpload = (file) => {
  if (!file || !file.raw) {
    ElMessage.error('文件无效');
    return;
  }

  const fileName = file.name.toLowerCase();
  const fileSize = file.raw.size;
  
  // 检查文件大小 (限制为10MB)
  if (fileSize > 10 * 1024 * 1024) {
    ElMessage.error('文件过大，请选择小于10MB的文件');
    return;
  }
  
  // 检查文件类型
  if (!fileName.endsWith('.txt') && !fileName.endsWith('.csv') && 
      !fileName.endsWith('.xlsx') && !fileName.endsWith('.xls')) {
    ElMessage.error('不支持的文件类型，请上传TXT、CSV或Excel文件');
    return;
  }
  
  const reader = new FileReader();
  
  reader.onload = (e) => {
    try {
      let content = '';
      
      if (fileName.endsWith('.txt') || fileName.endsWith('.csv')) {
        content = e.target.result;
        if (fileName.endsWith('.csv')) {
          // 简单CSV处理 - 仅提取第一列
          content = content.split('\n')
            .map(line => line.split(',')[0].replace(/"/g, '').trim())
            .filter(line => line)
            .join('\n');
        }
      } else if (fileName.endsWith('.xlsx') || fileName.endsWith('.xls')) {
        // Excel处理
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        
        // 提取第一列数据
        content = jsonData
          .map(row => row[0] ? String(row[0]).trim() : '')
          .filter(item => item)
          .join('\n');
      }
      
      if (content) {
        productTextarea.value = content;
        ElMessage.success(`成功导入${productCount.value}条商品数据`);
      } else {
        ElMessage.error('无法读取文件内容或文件为空');
      }
    } catch (error) {
      console.error('文件处理错误:', error);
      ElMessage.error('文件处理错误: ' + error.message);
    }
  };
  
  reader.onerror = () => {
    ElMessage.error('读取文件失败');
  };
  
  if (file.raw.type === 'text/plain' || file.raw.type === 'text/csv') {
    reader.readAsText(file.raw);
  } else {
    reader.readAsArrayBuffer(file.raw);
  }
};

// 上一步，添加防抖处理
const prevStep = () => {
  if (activeStep.value > 0 && !isStepTransitioning.value) {
    isStepTransitioning.value = true;
    
    // 先重置表格显示状态，避免视图切换时的ResizeObserver问题
    isTableReady.value = false;
    
    // 延迟执行步骤切换
    setTimeout(() => {
      activeStep.value--;
      
      // 延迟重新显示表格
      setTimeout(() => {
        isTableReady.value = true;
        isStepTransitioning.value = false;
      }, 300);
    }, 50);
  }
};

// 下一步，添加防抖处理
const nextStep = () => {
  if (isStepTransitioning.value) return;
  
  if (activeStep.value === 0) {
    // 如果是第一步，执行提取操作
    handleExtract();
  } else if (activeStep.value === 1) {
    // 从提取结果到确认新品牌
    isStepTransitioning.value = true;
    
    // 先重置表格显示状态
    isTableReady.value = false;
    
    setTimeout(() => {
      activeStep.value = 2;
      
      // 延迟重新显示表格
      setTimeout(() => {
        isTableReady.value = true;
        isStepTransitioning.value = false;
      }, 300);
    }, 50);
  } else if (activeStep.value === 2) {
    // 从确认新品牌到完成
    handleSaveBrands();
  }
};

// 计算表格高度，使用固定值而不是动态计算的值
const tableHeight = computed(() => {
  // 避免动态计算，使用固定高度
  return '350px';
});

// 延迟加载标志，避免初始化时的多次重绘
const isTableReady = ref(false);
// 防止步骤切换时的重绘问题
const isStepTransitioning = ref(false);

// 在组件挂载时使用增强的错误处理和初始化
onMounted(() => {
  // 使用全局错误处理工具
  suppressResizeObserverErrors();
  
  // 延迟一点执行，确保组件已完全渲染
  nextTick(() => {
    // 如果是页面模式则强制全屏
    if (props.pageMode) {
      isFullscreen.value = true;
    }
    
    // 延迟设置表格就绪状态，避免初始化阶段的ResizeObserver错误
    setTimeout(() => {
      isTableReady.value = true;
    }, 800); // 延长到800ms确保完全加载
  });
});

// 提取潜在品牌
const handleExtract = async () => {
  try {
    // 验证是否有输入
    if (productCount.value === 0) {
      ElMessage.warning('请先输入商品名称或上传文件');
      return;
    }
    
    loading.value.extract = true;
    loading.value.allSteps = true;
    isStepTransitioning.value = true;
    
    // 解析商品名称
    const productNames = productTextarea.value
      .split('\n')
      .map(line => line.trim())
      .filter(line => line.length > 0);
    
    console.log(`准备提取 ${productNames.length} 个商品的品牌信息`);
    
    // 分批处理，每次处理100个商品
    const batchSize = 100;
    const totalBatches = Math.ceil(productNames.length / batchSize);
    let processedCount = 0;
    let successCount = 0;
    extractedBrands.value = [];
    
    try {
      // 逐批处理数据
      for (let i = 0; i < totalBatches; i++) {
        const start = i * batchSize;
        const end = Math.min(start + batchSize, productNames.length);
        const batchData = productNames.slice(start, end);
        
        console.log(`处理批次 ${i+1}/${totalBatches}, 商品数量: ${batchData.length}`);
        
        // 最多重试3次
        let retryCount = 0;
        let success = false;
        let lastError = null;
        
        while (retryCount < 3 && !success) {
          try {
            const response = await extractBrands({
              product_names: batchData,
              use_hanlp: true,
              retry_count: retryCount // 告诉后端这是第几次重试
            });
            
            if (response.success) {
              processedCount += batchData.length;
              successCount++;
              
              // 假设响应中包含提取到的品牌
              if (response.data && response.data.brands) {
                // 转换API返回的数据格式为组件中使用的格式
                const brandData = response.data.brands.map(brand => ({
                  brandName: brand.name,
                  confidence: brand.confidence || 0.5,
                  matchCount: brand.count || 1,
                  examples: brand.examples || []
                }));
                
                extractedBrands.value = [...extractedBrands.value, ...brandData];
              }
              
              success = true;
              
              // 显示进度
              const progress = Math.round((processedCount / productNames.length) * 100);
              ElMessage({
                type: 'info',
                message: `已处理 ${processedCount}/${productNames.length} 个商品 (${progress}%)`,
                duration: 2000
              });
            } else {
              throw new Error(response.message || '提取失败');
            }
          } catch (error) {
            lastError = error;
            retryCount++;
            console.warn(`批次 ${i+1} 处理失败，重试 (${retryCount}/3): `, error);
            
            // 如果不是超时错误，不再重试
            if (error.code !== 'ECONNABORTED') {
              break;
            }
            
            // 等待一段时间再重试
            await new Promise(resolve => setTimeout(resolve, 2000));
          }
        }
        
        // 如果重试后仍然失败，提示但继续处理其他批次
        if (!success) {
          console.error(`批次 ${i+1} 处理失败（已重试${retryCount}次）:`, lastError);
          
          // 更新界面时间反馈
          ElMessage({
            type: 'warning',
            message: `批次 ${i+1} 处理失败，但将继续处理其他数据`,
            duration: 3000
          });
        }
      }
      
      // 如果至少有一个批次成功，就进入下一步
      if (successCount > 0) {
        // 先重置表格显示状态
        isTableReady.value = false;
        
        setTimeout(() => {
          activeStep.value = 1;
          
          // 为了测试，如果API没有返回数据，添加一些模拟数据
          if (extractedBrands.value.length === 0) {
            extractedBrands.value = [
              { brandName: '苹果', confidence: 0.95, matchCount: 15, examples: ['苹果iPhone 14', '苹果MacBook Pro'] },
              { brandName: '三星', confidence: 0.92, matchCount: 12, examples: ['三星Galaxy S21', '三星显示器'] },
              { brandName: '华为', confidence: 0.90, matchCount: 18, examples: ['华为P40', '华为MateBook'] },
              { brandName: '小米', confidence: 0.88, matchCount: 14, examples: ['小米11', '小米手环'] },
              { brandName: '联想', confidence: 0.85, matchCount: 10, examples: ['联想ThinkPad', '联想拯救者'] }
            ];
          }
          
          // 延迟重新显示表格
          setTimeout(() => {
            isTableReady.value = true;
            isStepTransitioning.value = false;
            ElMessage.success(`成功提取品牌信息，共发现 ${extractedBrands.value.length} 个潜在品牌`);
          }, 300);
        }, 50);
      } else {
        ElMessage.error('所有批次处理均失败，请稍后重试');
        isStepTransitioning.value = false;
      }
    } catch (error) {
      console.error('API调用错误:', error);
      isStepTransitioning.value = false;
      
      // 提供更友好的错误信息
      if (error.code === 'ECONNABORTED') {
        ElMessage.error(`请求超时，服务器处理时间过长。建议减少数据量或稍后重试。`);
      } else {
        ElMessage.error(`提取失败: ${error.message || '未知错误'}`);
      }
    }
  } catch (error) {
    console.error('提取出错:', error);
    ElMessage.error('提取失败: ' + error.message);
    isStepTransitioning.value = false;
  } finally {
    loading.value.extract = false;
    loading.value.allSteps = false;
  }
};

// 保存品牌
const handleSaveBrands = async () => {
  try {
    loading.value.save = true;
    loading.value.allSteps = true;
    isStepTransitioning.value = true;
    
    if (confirmedBrands.value.length === 0) {
      ElMessageBox.confirm('您尚未确认任何品牌，确定要继续吗？', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '返回编辑',
        type: 'warning'
      }).then(() => {
        // 继续保存操作
        performSaveBrands();
      }).catch(() => {
        loading.value.save = false;
        loading.value.allSteps = false;
        isStepTransitioning.value = false;
      });
    } else {
      performSaveBrands();
    }
  } catch (error) {
    console.error('保存出错:', error);
    ElMessage.error('保存失败: ' + error.message);
    loading.value.save = false;
    loading.value.allSteps = false;
    isStepTransitioning.value = false;
  }
};

// 执行保存品牌操作
const performSaveBrands = async () => {
  try {
    // 构建保存数据
    const brandsToSave = confirmedBrands.value.map(brand => ({
      name: brand.brandName,
      category: brand.category,
      confidence: brand.confidence
    }));
    
    console.log('保存品牌操作...', brandsToSave);
    
    // 调用API保存品牌
    const response = await saveBrands(brandsToSave);
    
    if (response.success) {
      // 保存非品牌数据（被拒绝的品牌）
      if (extractedBrands.value.length > 0) {
        const nonBrands = extractedBrands.value.map(brand => brand.brandName);
        try {
          await addToNonBrands(nonBrands);
        } catch (error) {
          console.warn('保存非品牌数据失败:', error);
        }
      }
      
      // 重置表格显示状态
      isTableReady.value = false;
      
      setTimeout(() => {
        // 成功后进入完成步骤
        activeStep.value = 3;
        
        // 发送完成事件
        handleComplete({
          added_brands: confirmedBrands.value.map(brand => brand.brandName)
        });
        
        setTimeout(() => {
          isTableReady.value = true;
          isStepTransitioning.value = false;
          ElMessage.success('品牌保存成功');
        }, 300);
      }, 50);
    } else {
      throw new Error(response.message || '保存失败');
    }
  } catch (error) {
    console.error('API调用错误:', error);
    ElMessage.error('保存失败: ' + (error.message || '未知错误'));
    isStepTransitioning.value = false;
  } finally {
    loading.value.save = false;
    loading.value.allSteps = false;
  }
};

// 处理完成操作
const handleComplete = (result) => {
  // 发送完成事件
  emit('complete', {
    success: true,
    addedCount: result.added_brands ? result.added_brands.length : 0,
    needsRefresh: true
  });
  
  // 如果非页面模式，则关闭对话框
  if (!props.pageMode) {
    dialogVisible.value = false;
  }
};
</script>

<style scoped>
.brand-extractor {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif;
}

.main-container {
  margin-top: 10px;
  margin-bottom: 10px;
  height: auto; /* 不使用动态计算的高度 */
  min-height: 500px; /* 使用最小高度保证空间足够 */
  display: flex;
  flex-direction: column;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.dialog-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.top-action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.step-container {
  margin-top: 10px;
  min-height: 50px;
  /* height: calc(100% - 100px); */
  display: flex;
  flex-direction: column;
}

.step-container > div:not(.loading-container) {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.step-description {
  margin-bottom: 15px;
  color: #606266;
}

.textarea-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  font-size: 0.9em;
  color: #909399;
}

.file-type-hint {
  margin-top: 5px;
  font-size: 0.8em;
  color: #909399;
}

.loading-container {
  padding: 20px;
  text-align: center;
}

.extract-results {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  height: auto; /* 从计算高度改为自动 */
}

.result-summary {
  margin-bottom: 20px;
}

.brand-lists {
  display: flex;
  gap: 20px;
  margin-top: 10px;
  padding-bottom: 20px;
}

.known-brands, .unknown-brands {
  flex: 1;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  display: flex;
  flex-direction: column;
  min-height: 300px;
  max-height: 600px;
  overflow-y: auto;
}

h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #303133;
}

.no-selection-hint {
  margin: 20px 0;
}

.confirm-brands {
  margin-top: 15px;
}

.brand-category-selector {
  margin: 20px 0;
}

.category-label {
  margin-right: 10px;
}

.completion-container {
  text-align: center;
  padding: 20px;
}

.save-results {
  text-align: left;
  max-width: 600px;
  margin: 0 auto;
}

.added-brands, .skipped-brands {
  margin-top: 15px;
  padding: 10px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}

.action-buttons {
  margin-bottom: 10px;
}

.action-description {
  margin-bottom: 10px;
}

.pagination {
  margin-top: 15px;
  margin-bottom: 10px;
  display: flex;
  justify-content: center;
}

.unknown-brands-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.unknown-brands-actions {
  display: flex;
  gap: 10px;
}

.info-icon {
  cursor: pointer;
}

.known-brands-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.brand-input-wrapper {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.brand-status-indicators {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 4px;
  flex-wrap: wrap;
}

.confidence-tag {
  font-size: 11px;
  padding: 0 5px;
  height: 20px;
  line-height: 18px;
}

.confidence-high {
  color: #67c23a;
}

.confidence-medium {
  color: #409eff;
}

.confidence-low {
  color: #e6a23c;
}

.feedback-indicator {
  font-size: 12px;
  line-height: 1;
}

.positive-feedback {
  color: #67c23a;
}

.negative-feedback {
  color: #f56c6c;
}

.filter-config-panel {
  margin-bottom: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.form-help-text {
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}

/* 添加页面模式样式 */
.page-mode-container {
  width: 100%;
  min-height: 50vh;
  padding: 20px;
  background-color: #fff;
}

.page-mode-container .main-container {
  min-height: 50vh;
}

.step-buttons {
  margin-top: 20px;
  text-align: right;
}

.upload-area {
  display: inline-block;
}

.file-type-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.input-container {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
}
</style> 